using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using UniversalAdmin.Api.Models;
using UniversalAdmin.Application.Common;
using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Application.Services;
using UniversalAdmin.Domain.Enums;

namespace UniversalAdmin.Api.Controllers;

[ApiController]
[Route("api/articles")]
public class ArticlesController : ControllerBase
{
  private readonly IArticleService _articleService;
  private readonly IAuthService _authService;

  public ArticlesController(IArticleService articleService, IAuthService authService)
  {
    _articleService = articleService;
    _authService = authService;
  }

  private int GetUserId()
  {
    var idClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
    return int.TryParse(idClaim, out var id) ? id : throw new UnauthorizedAccessException();
  }

  private async Task<IEnumerable<string>> GetUserRolesAsync()
  {
    return await _authService.GetUserRolesAsync(GetUserId());
  }

  [HttpGet]
  public async Task<IActionResult> GetArticles(
      [FromQuery] string? keyword,
      [FromQuery] int? categoryId,
      [FromQuery] ArticleStatus? status,
      [FromQuery] int page = 1,
      [FromQuery] int size = 10)
  {
    var result = await _articleService.GetArticlesAsync(keyword, categoryId, status, page, size);
    return Ok(ApiResponse<PagedResult<ArticleListDto>>.Success(result));
  }

  [HttpGet("{id:int}")]
  public async Task<IActionResult> GetArticle(int id)
  {
    var article = await _articleService.GetArticleByIdAsync(id);
    if (article == null) return NotFound();
    return Ok(ApiResponse<ArticleDto>.Success(article));
  }

  [HttpGet("search")]
  public async Task<IActionResult> Search(
        [FromQuery] string? keyword = null,
        [FromQuery] ArticleStatus? status = null,
        [FromQuery] DateTime? start = null,
        [FromQuery] DateTime? end = null,
        [FromQuery] int page = 1,
        [FromQuery] int size = 10)
  {
    // 处理日期时区问题，将本地日期转换为UTC
    DateTime? utcStart = null;
    DateTime? utcEnd = null;
    
    if (start.HasValue)
    {
      // 如果是未指定时区的日期，假设为本地时间并转换为UTC
      if (start.Value.Kind == DateTimeKind.Unspecified)
      {
        utcStart = DateTime.SpecifyKind(start.Value, DateTimeKind.Local).ToUniversalTime();
      }
      else
      {
        utcStart = start.Value.ToUniversalTime();
      }
    }
    
    if (end.HasValue)
    {
      // 如果是未指定时区的日期，假设为本地时间的一天结束时间并转换为UTC
      if (end.Value.Kind == DateTimeKind.Unspecified)
      {
        var endOfDay = DateTime.SpecifyKind(end.Value.Date.AddDays(1).AddTicks(-1), DateTimeKind.Local);
        utcEnd = endOfDay.ToUniversalTime();
      }
      else
      {
        utcEnd = end.Value.Date.AddDays(1).AddTicks(-1).ToUniversalTime();
      }
    }

    var param = new ArticleQueryParameters
    {
      Keyword = keyword,
      Status = status,
      Start = utcStart,
      End = utcEnd,
      Page = page,
      Size = size
    };

    var res = await _articleService.SearchArticlesAsync(param);
    return Ok(ApiResponse<PagedResult<ArticleDto>>.Success(res, "查询成功"));
  }

  [HttpPost]
  [Authorize]
  public async Task<IActionResult> CreateArticle([FromBody] CreateArticleDto dto)
  {
    var userId = GetUserId();
    var result = await _articleService.CreateArticleAsync(dto, userId);
    return Ok(ApiResponse<ArticleDto>.Success(result, "创建成功"));
  }

  [HttpPut("{id:int}")]
  [Authorize]
  public async Task<IActionResult> UpdateArticle(int id, [FromBody] UpdateArticleDto dto)
  {
    var userId = GetUserId();
    var roles = await GetUserRolesAsync();
    var result = await _articleService.UpdateArticleAsync(id, dto, userId, roles);
    return Ok(ApiResponse<ArticleDto>.Success(result, "更新成功"));
  }

  [HttpDelete("{id:int}")]
  [Authorize]
  public async Task<IActionResult> DeleteArticle(int id)
  {
    var userId = GetUserId();
    var roles = await GetUserRolesAsync();
    await _articleService.DeleteArticleAsync(id, userId, roles);
    return Ok(ApiResponse.Success("删除成功"));
  }
}